#include "serialconnection.h"
#include "QDebug"

SerialConnection::SerialConnection(QObject *parent) :
        QObject(parent)
{
    port = new QextSerialPort(COMPORT);
    connect(&timer_usart,SIGNAL(timeout()),this,SLOT(receiveMsg())); // Slot for UART Polling
    timer_usart.setInterval(50);
}

SerialConnection::~SerialConnection()
{
    delete port;
}

bool SerialConnection::openPort(QString portName, BaudRateType baudrate)
{
    port->setPortName(portName);
    if(port->open(QIODevice::ReadWrite)){

        port->setFlowControl(FLOWCONTROL);
        port->setParity(PARITY);
        port->setDataBits(DATABITS);
        port->setStopBits(STOPBITS);
        port->setTimeout(PORT_TIMEOUT);
        port->setBaudRate(baudrate);

        qDebug("is open: %d", port->isOpen());
        timer_usart.start();
        return true;
    }

    qDebug("is open: %d", port->isOpen());
    return false;
}

void SerialConnection::closePort()
{
    timer_usart.stop();
    port->close();
    qDebug("is open: %d", port->isOpen());
}

void SerialConnection::transmitMessage(QString msg)
{
    int i = port->write(msg.toAscii(), msg.length());
    port->flush();
    qDebug() << "transmitted:" << i << ": " << qPrintable(msg);
}

void SerialConnection::transmitMessage(char* buffer, int length)
{
    int i = port->write(buffer, length);
    port->flush();
    qDebug() << "transmitted:" << i; // << ": " << QString::fromAscii(buffer, length);
//    printf("str2: %s", buffer);
}

void SerialConnection::receiveMsg()
{
    char buff[1025];
    int numBytes,i;

    // Read 1kb from Port
    while((numBytes = port->bytesAvailable())>0){
        if(numBytes > 1024)
            numBytes = 1024;

        i = port->read(buff, numBytes);
        input_buffer.append(buff,i);
        MsgReceived(&input_buffer);
    }
}
